#include <iostream>
#include <pthread.h>

using namespace std;

class sluggard
{
    public:
        ~sluggard()
        {
            pthread_mutex_destroy(&mutex_);
        }

        static sluggard* getsl();
        
        void test()
        {
            cout<<999<<endl;
        }
    private:
        sluggard()
        {}
        static pthread_mutex_t mutex_;
        static sluggard* sl;
};

//懒汉模式
sluggard* sluggard::sl = NULL;
pthread_mutex_t sluggard::mutex_ = PTHREAD_MUTEX_INITIALIZER;
sluggard* sluggard::getsl()
{
    //这里判断可以避免在创建好了之后别的线程进行无效的抢锁
    if(sl == NULL){
        pthread_mutex_lock(&mutex_);
        //这里的判断是必须的防止第一次创建对象时有多个线程抢锁
        if(sl == NULL){
            sl = new sluggard;
        }
        pthread_mutex_unlock(&mutex_);
    };
    return sl;
}

int main()
{
    sluggard* sl = sluggard::getsl();
    sl->test();
    return 0;
}
